package com.servlet;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.util.*;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageCode extends HttpServlet {
	
	private InputStream image;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		Map<String, BufferedImage> map = ImageCodeUtil.getImage();
		String code = map.keySet().iterator().next();
		Log.write(code);
		BufferedImage bi = map.get(code);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
		try {
			encoder.encode(bi);
			image = new ByteArrayInputStream(baos.toByteArray());

			HttpSession session = request.getSession(true);
			session.setAttribute("currcode", code);
		
			response.setContentType("Image/jpeg");
			
			OutputStream outS = response.getOutputStream();
		    
	        // Copy the contents of the file to the output stream
	        byte[] buf = new byte[1024];
	        int count = 0;
	        while ((count = image.read(buf)) >= 0) {
	        	outS.write(buf, 0, count);
	        }
	        image.close();
	        outS.close();
        
		} catch (Exception e) {
		}
		
		//out.println(image);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	public void setImage(InputStream image) {
		this.image = image;
	}
	public InputStream getImage() {
		return image;
	}

}
